﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace TCPListener
{
    class Program
    {
        private static int m_sendSize = 172032;

        static void Main(string[] args)
        {
            TcpListener server = null;
            try
            {
                // Set the TcpListener on port 13000.
                Int32 port = 13000;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[m_sendSize];

                String data = null;

                int fileCount = 0;
                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    BinaryWriter bWrite = new BinaryWriter(File.Open(string.Format(@"Files\{0}.avi", fileCount), FileMode.OpenOrCreate));
                    // Loop to receive all the data sent by the client.
                    long totalBytes = 0;
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        totalBytes += i;
                        Console.WriteLine("Retrived {0,-12} bytes", i);
                        bWrite.Write(bytes, 0, i);  
                    }
                    Console.WriteLine("Total Retrived {0,-12} bytes", totalBytes);
                    bWrite.Close();
                    // Shutdown and end connection
                    client.Close();

                    ++fileCount;
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }


            Console.WriteLine("\nHit enter to continue...");
            Console.Read();

        }
    }
}
